DROP TABLE #TEST
CREATE TABLE #TEST (TEST_ID INT IDENTITY(1,1))

DECLARE @rowNumber smallint
SET IDENTITY_INSERT #TEST ON
SET @rowNumber = 1;
WHILE(@rowNumber <= 100)
BEGIN
	INSERT INTO #TEST(TEST_ID) VALUES(@rowNumber)
	SET @rowNumber = @rowNumber + 1
END
SELECT * FROM #TEST

DROP TABLE #TEST
CREATE TABLE #TEST (COL1 VARCHAR(10), COL2 SMALLDATETIME NULL)
INSERT INTO #TEST VALUES ('FA','2008-10-01')
INSERT INTO #TEST VALUES ('BB',NULL)
INSERT INTO #TEST VALUES ('CD','2007-05-20')
INSERT INTO #TEST VALUES ('AA',NULL)
INSERT INTO #TEST VALUES ('XZ','2008-10-01')

SELECT * FROM #TEST 
ORDER BY CASE WHEN COL2 IS NULL THEN 1 ELSE 0 END, COL2, COL1

DROP TABLE #TEST
CREATE TABLE #TEST (ID TINYINT NULL, COL1 CHAR(1))
INSERT INTO #TEST (ID,COL1) VALUES (1,'A')
INSERT INTO #TEST (ID,COL1) VALUES (2,'B')
INSERT INTO #TEST (ID,COL1) VALUES (1,'A')
INSERT INTO #TEST (ID,COL1) VALUES (1,'B')

SELECT ID, COL1, COL2=count(*)
INTO #TEMP_TEST
FROM #TEST
GROUP BY ID, COL1
HAVING count(ID) > 1

Select * from #TEMP_TEST

Select * from #TEST

DELETE #TEST
FROM #TEST, #TEMP_TEST
WHERE #TEST.ID = #TEMP_TEST.ID
AND #TEST.COL1 = #TEMP_TEST.COL1

INSERT INTO #TEST(ID, COL1) SELECT ID, COL1 FROM #TEMP_TEST

DROP TABLE #TEMP_TEST

SELECT * from #TEST


CREATE TABLE [NAMES]([ID] [int], [NAME] [varchar](100))
INSERT [NAMES] VALUES (1,'FRANK')
INSERT [NAMES] VALUES (2,'JO')
INSERT [NAMES] VALUES (3,'MARY')
INSERT [NAMES] VALUES (4,'PETER')
INSERT [NAMES] VALUES (5,'MAY')

CREATE TABLE [RELATIONSHIPS]([NAMEID] [int], [PARENT_NAMEID] [int])
INSERT [RELATIONSHIPS] VALUES (1,0)
INSERT [RELATIONSHIPS] VALUES (2,1)
INSERT [RELATIONSHIPS] VALUES (3,2)
INSERT [RELATIONSHIPS] VALUES (4,1)
INSERT [RELATIONSHIPS] VALUES (5,2)

select * from NAMES
select * from RELATIONSHIPS

;With RN([Level], ID, Name)
	As
	(
	  SELECT 0 AS Level, N.ID, N.NAME
	    FROM RELATIONSHIPS R INNER JOIN NAMES N ON R.NAMEID = N.ID
	    WHERE R.PARENT_NAMEID = 0
	  UNION ALL
	  SELECT R.PARENT_NAMEID, N.ID, N.NAME
	    FROM RELATIONSHIPS R INNER JOIN NAMES N ON R.NAMEID = N.ID
	    INNER JOIN RN ON RN.ID = R.PARENT_NAMEID
	)
	 
	SELECT RN.Level, RN.ID, RN.Name
	FROM RN
	ORDER BY RN.Name
	  

Drop Table #TEST
CREATE TABLE #TEST (ID INT, SEGMENT CHAR(1),RESPONSES INT,CHECKED SMALLDATETIME)
INSERT INTO #TEST VALUES (1,'A',0,'2009-05-01')
INSERT INTO #TEST VALUES (2,'B',1,'2009-05-01')
INSERT INTO #TEST VALUES (3,'C',0,'2009-05-01')
INSERT INTO #TEST VALUES (4,'A',0,'2009-05-02')
INSERT INTO #TEST VALUES (5,'B',2,'2009-05-02')
INSERT INTO #TEST VALUES (6,'C',1,'2009-05-02')
INSERT INTO #TEST VALUES (7,'A',1,'2009-05-03')
INSERT INTO #TEST VALUES (8,'B',0,'2009-05-03')
INSERT INTO #TEST VALUES (9,'C',2,'2009-05-03')

SELECT *
FROM
(
    SELECT CHECKED, RESPONSES, SEGMENT
    FROM #TEST
) AS SourceTable
PIVOT
(
    Sum(RESPONSES)
    FOR [Segment] IN ([A], [B], [C])
 )AS PivotTable












